package com.qdlc.p2p.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.RoleService;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.RoleDao;
import com.qdlc.p2p.dal.dao.RoleMenuDao;
import com.qdlc.p2p.dal.dto.Menu;
import com.qdlc.p2p.dal.dto.Role;
import com.qdlc.p2p.dal.dto.RoleMenu;
import com.qdlc.p2p.dal.model.RoleModel;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

    /**
     * 角色DAO
     */
    @Resource
    private RoleDao roleDao;

    /**
     * 角色菜单DAO
     */
    @Resource
    private RoleMenuDao roleMenuDao;

    public PageDataList<Role> list(RoleModel model) {
        return roleDao.list(model);
    }

    public void addRole(Role role, String[] menuIdArr) {
        role.setUpdateTime(DateUtil.getNow());
        role.setAddTime(DateUtil.getNow());
        Role r = roleDao.save(role);
        for (int i = 0; i < menuIdArr.length; i++) {
            String menuIdStr = menuIdArr[i];
            long menuId = Long.parseLong(menuIdStr);
            Menu menu = new Menu(menuId);
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenu(menu);
            roleMenu.setRole(r);
            roleMenuDao.save(roleMenu);
        }
    }

    public Role getRoleById(long id) {
        return roleDao.roleFind(id);
    }

    public void roleUpdate(Role role) {
        role.setUpdateTime(DateUtil.getNow());
        roleDao.update(role);
    }

    public List<Role> getRoleList() {
        return roleDao.roleList();
    }

    public void deleteRole(long id) {
        Role role = roleDao.roleFind(id);
        if (role == null) {
            return;
        }
        role.setUpdateTime(DateUtil.getNow());
        role.setDelete(true);
        roleDao.update(role);
    }

    public void roleMenuUpdate(long roleId, String[] menuIdArr) {
        Role r = roleDao.roleFind(roleId);
        if (r == null) {
            return;
        }
        roleMenuDao.deleteByRoleId(roleId);
        for (int i = 0; i < menuIdArr.length; i++) {
            String menuIdStr = menuIdArr[i];
            long menuId = Long.parseLong(menuIdStr);
            Menu menu = new Menu(menuId);
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenu(menu);
            roleMenu.setRole(r);
            roleMenuDao.save(roleMenu);
        }
    }

    public List<Role> getRoleList(long userId) {
        return roleDao.getRoleList(userId);
    }
}
